package ks.app.smartDic;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;

public class UpdateNotifier extends AsyncTask<String, String, String> {
	int systemVersionCode;
	Context context;
	AlertDialog dialog;
	Boolean isUpdatable;

	private static final String url = "http://hydra01.woweb.net/cloud/getSmartDicVersionCode.php";
	private static Boolean DEBUG = false;

	UpdateNotifier(Context pContext) {
		context = pContext;
		
		isUpdatable = false;

		dialog = new AlertDialog.Builder(context)
				.setIcon(R.drawable.smartdic_icon)
				.setTitle("업데이트 알림")
				.setMessage("새로운 업데이트가 있습니다.\n업데이트 하시겠습니까? ^^")
				.setPositiveButton("업데이트", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

						Intent goToMarket = null;
						goToMarket = new Intent(Intent.ACTION_VIEW, Uri
								.parse("market://details?id="
										+ context.getPackageName()));
						context.startActivity(goToMarket);

					}
				})
				.setNegativeButton("취소", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				}).create();

	}

	@Override
	protected String doInBackground(String... params) {

		try {

			this.systemVersionCode = getVersionCode();
			if (isNetworkAvailable())
				isUpdatable = IsUpdatable();

		} catch (Exception e) {
			ksLog.d("update exception",e.getMessage());
		}

		return null;
	}

	@Override
	protected void onPostExecute(String result) {

		if (isUpdatable)
			dialog.show();

	}

	Boolean IsUpdatable() {
		int versionNo = -1;

		if (DEBUG)
			return true;

		httpClient hp = new httpClient();

		try {
			versionNo = Integer.parseInt(hp.postAndGetStr(url));
		} catch (Exception e) {
			ksLog.d("parse exception", e.getMessage());
			return false;
		}

		if (systemVersionCode < versionNo)
			return true;
		else
			return false;

	}

	public int getVersionCode() {
		int versionCode = -1;

		try {
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (Exception e) {
			ksLog.d("versionException", e.getMessage());
		}

		return versionCode;
	}

	private Boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		return cm.getActiveNetworkInfo().isAvailable();
	}

}
